// import { upFileToOss } from '@Utils/getPageDecrypt'
import {
  getCatePropertyV2Api,
  publishProductApi,
  uploadMaterialApi
} from "@Api/sysApi/productApi"
import {
  Button,
  Checkbox,
  Divider,
  Drawer,
  Empty,
  Form,
  Icon,
  ImgDefault,
  Input,
  InputNumber,
  message,
  Modal,
  Popover,
  Progress,
  Radio,
  Select,
  Space,
  Spin,
  Steps,
  Switch,
  Tooltip
} from "@bytedance/mona-ui"
import type { CheckboxChangeEvent } from "@bytedance/mona-ui/es/components/checkbox"
import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState
} from "react"

import { useAppDispatch, useAppSelector } from "~store"
import { AutoTk } from "~store/controller/funcTabs"
import {
  setCopyGoodConfigAction,
  setDddHuohaoContent,
  setDetailsAddImageList,
  setRefoterZhutuStatusState,
  setZhutuAddImageList
} from "~store/controller/jinritemaiCopyGoods"

import AddBodersContent from "./AddBodersContent"
import AddBodersContent34 from "./AddBodersContent34"
import AddDetailsContent from "./AddDetailsContent"
import {
  asycGetImageStatus,
  generateRandomString,
  setImageInfoDtatFun,
  shuffleArray
} from "./copyDataFomate"
import PriceAndInventory from "./PriceAndInventory"
import SkuTitleInfoData from "./SkuTitleInfoData.tsx"
import StatsList from "./StatsList.tsx"
import TitleJieba from "./TitleJieba"
import TitleJiebaShers from "./TitleJiebaShers"

import "./index.scss"

import { config } from "dotenv"

const { Option } = Select
const ossurl = process.env.PLASMO_PUBLIC_CN_OSS
// import OSS from 'ali-oss'

// Icon.addSvgSymbolIcon(SuccessSvg)

const { Step } = Steps

function getStrLen(str) {
  var charsToReplace = ["～", "！", "¥", "（", "）", "【", "】", "「", "」"]

  // 将数组元素用管道符(|)连接，创建一个正则表达式
  var regex = new RegExp(charsToReplace.join("|"), "g")

  return str.replace(regex, "a").replace(/[^\x00-\xff]/g, "aa").length
}

function getMoveItemInfo(getitrem: number, bi) {
  let mobeInfo = {}
  switch (getitrem) {
    case 1:
      mobeInfo = {
        left: 5,
        top: 5,
        offseX: 5,
        offsetY: 5,
        width: 15,
        height: Math.round(bi * 15)
      }
      break
    case 2:
      mobeInfo = {
        left: 0,
        top: 0,
        offseX: 0,
        offsetY: 0,
        width: 100,
        height: 100
      }
      break
    default:
      break
  }
  return mobeInfo
}
// 弹窗主表单
const ShowDataBox = forwardRef((props: any, ref) => {
  const {
    goodsDetellData,
    goodPrettify,
    titleJfrStart,
    searchWord,
    searchWordMsg,
    statsDataList,
    ruleData
  } = props
  // console.log('匹配的规则', ruleData)
  // console.log('属性', goodsDetellData.addRequData)
  // console.log('statsDataList', statsDataList)
  // console.log('ruleData', ruleData)
  // console.log('searchWordMsg', searchWordMsg)
  interface copyGoodConfigType {
    copynum: number // 裂变数量
    goodTitleCf: number // 商品标题
    statsCf: number // 商品属性
    goodMiniTitle: boolean // 导购标题
    goodMiniTitleCf: number // 导购标题单选项
    goodImageCf: number // 主图但选项
    goodImage34: boolean // 主图3：4
    goodImage34Cf: number // 主图3：4 单选项
    goodminivideo: boolean // 主图视频
    goodWhitehImage: boolean // 白底图
    goodWhitehImageCf: number // 白底图 单选项
    // goodDetelesImage: boolean // 商品详情
    goodDetelesImageCf: number // 商品详情 单选项
    goodSpcter: boolean // 商品规格
    goodSpcterCf: number // 商品规格 单选项
    goodPriceAndStock: boolean // 价格与库存
    goodPriceAndStockCf: number // 价格与库存 单选项
  }
  const [copyGoodConfig, setCopyGoodConfig] = useState<copyGoodConfigType>({
    copynum: 5,
    goodTitleCf: 2,
    statsCf: 1,
    goodMiniTitle: false,
    goodMiniTitleCf: 1,
    goodImageCf: 2,
    goodImage34: false,
    goodImage34Cf: 1,
    goodminivideo: false,
    goodWhitehImage: false,
    goodWhitehImageCf: 1,
    // goodDetelesImage: false,
    goodDetelesImageCf: 2,
    goodSpcter: true,
    goodSpcterCf: 2,
    goodPriceAndStock: true,
    goodPriceAndStockCf: 2
  })
  const [requdata, setRequData] = useState(goodsDetellData.addRequData)

  // 需要添加修改属性
  const [addNewProd, setNewProd] = useState(
    goodsDetellData.newprodata.length ? [goodsDetellData.newprodata] : []
  )
  const [addAllNewProd, setAllNewProd] = useState("")
  const [reduterHuoDate, setReduterHuoDate] = useState(10)
  const [showAddHuohao, setShowAddHuohao] = useState(false)
  // const [addHuohao, setAddHuohao] = useState('')
  // const [reduterHuoDate2, setreduterHuoDate2] = useState(false)
  // console.log('需要添加修改属性', addNewProd)

  const dispatch = useAppDispatch()
  useEffect(() => {
    // console.log('修改数据****', copyGoodConfig)
    dispatch(
      setCopyGoodConfigAction(JSON.parse(JSON.stringify(copyGoodConfig)))
    )
    if (
      copyGoodConfig.copynum === addNewProd.length ||
      !goodsDetellData.newprodata.length
    ) {
      return
    }
    const addConter = copyGoodConfig.copynum - addNewProd.length
    if (addConter > 0) {
      for (let i = 0; i < addConter; i++) {
        addNewProd.push(goodsDetellData.newprodata)
      }
    } else {
      addNewProd.splice(addConter, Math.abs(addConter))
    }
    setNewProd(JSON.parse(JSON.stringify(addNewProd)))
  }, [copyGoodConfig])
  // useEffect(() => {
  //   dispatch(setDddHuohaoContent(JSON.parse(JSON.stringify(addNewProd))))
  // }, [addNewProd])
  function getPricImageInfo(moveinfo: any) {
    const picImages =
      goodPrettify?.map((res: any, index: number) => {
        return {
          url: res,
          watermark: {
            ...moveinfo,
            bi: 0,
            pageX: 0,
            pageY: 0,
            url: null,
            moveStatus: false,
            clickTime: 0,
            setImageStatus: false,
            mergeurl: null
          },
          moveImageStatus: false,
          translateX: index * 120,
          left: 0,
          top: 0,
          pageX: 0,
          pageY: 0,
          zIndex: 1,
          elemCenterPx: 0,
          index
        }
      }) || []
    return picImages
  }
  function getZhutuPricImageInfo(moveinfo: any) {
    const picImages =
      goodsDetellData?.pic?.map((res: any, index: number) => {
        return {
          url: res,
          watermark: {
            ...moveinfo,
            bi: 0,
            pageX: 0,
            pageY: 0,
            url: null,
            moveStatus: false,
            clickTime: 0,
            setImageStatus: false,
            mergeurl: null
          },
          moveImageStatus: false,
          translateX: index * 120,
          left: 0,
          top: 0,
          pageX: 0,
          pageY: 0,
          zIndex: 1,
          elemCenterPx: 0,
          index
        }
      }) || []
    return picImages
  }
  const [picImageList, setPicImageList] = useState<any[]>([
    {
      config: {
        selectType: 1
      },
      list: getPricImageInfo(getMoveItemInfo(1, 0))
    }
  ])
  useEffect(() => {
    dispatch(setDetailsAddImageList(JSON.parse(JSON.stringify(picImageList))))
  }, [picImageList])

  function addImageItem(type) {
    const copLisco = {
      config: {
        selectType: type
      },
      list: getZhutuPricImageInfo(getMoveItemInfo(type, 0))
    }
    let puternu: any = []
    for (let i = 0; i < copyGoodConfig.copynum; i++) {
      puternu.push(copLisco)
    }
    return puternu
  }

  const [addZhutuImage, setAddZhutuImage] = useState(addImageItem(1))
  const [titleLimitRule, setTitleLimitRule] = useState({
    min_length: 15,
    max_length: 60
  })

  useEffect(() => {
    // console.log('addZhutuImage', addZhutuImage)
    dispatch(setZhutuAddImageList(JSON.parse(JSON.stringify(addZhutuImage))))
  }, [addZhutuImage])
  const [showJiaochngBox, setShowJiaochngBox] = useState(false)
  const [showErrContentA, setShowErrContentA] = useState(false)
  const [refoterZhutuStatus, setRefoterZhutuStatus] = useState(false)
  useEffect(() => {
    dispatch(setRefoterZhutuStatusState(refoterZhutuStatus))
    return
  }, [refoterZhutuStatus])
  const statsDataRef = useRef<any>(null)
  const skuDataRef = useRef<any>(null)
  const detailsAddImageListRef = useRef<any>(null)
  const getJiebaTitleRef = useRef<any>(null)
  const getAITitleRef = useRef<any>(null)
  const pricelistRef = useRef<any>(null)
  useImperativeHandle(ref, () => ({
    getdatersAllconte() {
      return statsDataRef.current && statsDataRef.current.getStatsDataList()
    },
    getSkudataAllconte() {
      // console.log(' skuDataRef.current.skuTextList', skuDataRef.current)
      return skuDataRef.current && skuDataRef.current.skuTextList
    },
    detailsAddImageListFunc() {
      return (
        detailsAddImageListRef.current &&
        detailsAddImageListRef.current.picImageList
      )
    },
    getJiebaTitle() {
      return getJiebaTitleRef.current && getJiebaTitleRef.current.refoConterData
    },
    getAiTitle() {
      return getAITitleRef.current && getAITitleRef.current.refoConterData
    },
    getLadderPriceList() {
      return pricelistRef.current && pricelistRef.current.ladderPrice
    },
    getPriceGroup() {
      return pricelistRef.current && pricelistRef.current.priceGroup
    },
    getFixedPriceList() {
      return pricelistRef.current && pricelistRef.current.fixedPrice
    },
    getAddHuohaoContent() {
      return addNewProd
    }
  }))
  return (
    <>
      <Form
        layout="vertical"
        initialValues={{
          ...copyGoodConfig
        }}>
        <h2
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between"
          }}>
          裂变基础配置
          <Button
            type="primary"
            icon={<Icon type="WarningLineIcon"></Icon>}
            onClick={() => {
              setShowJiaochngBox(true)
            }}>
            视频教程
          </Button>
        </h2>
        <Form.Item
          name="copynum"
          label="裂变数量"
          tooltip="将会裂变的总数量"
          rules={[{ required: true, message: "请输入裂变数量" }]}>
          <InputNumber
            placeholder="请输入需要裂变的数量"
            min={1}
            max={10}
            unit="条"
            onChange={(value: any) => {
              setCopyGoodConfig({ ...copyGoodConfig, copynum: value * 1 })
            }}
          />
        </Form.Item>

        {/* <Form.List name="sights"> */}
        {requdata &&
          requdata.length > 0 &&
          requdata.map((item: any, index: number) => {
            return (
              <Form.Item
                key={index}
                name={`addRequData[${index}]`}
                label={`${item.property_name}`}
                tooltip={`${item.property_name}`}
                rules={[
                  { required: true, message: `请输入${item.property_name}` }
                ]}>
                <div className="gotolink">
                  <span
                    style={{
                      color: "red"
                    }}>
                    该项为必填项，请完善后开始
                  </span>
                  <Button
                    type="link"
                    onClick={() => {
                      setShowErrContentA(true)
                    }}>
                    查看教程
                  </Button>
                </div>
                {/* {
                  item.type === "text" && <Input style={{ width: 240 }} placeholder={`请输入${item.property_name}`} />
                }
                {
                  item.type === "select" && <Select style={{ width: 240 }} placeholder={`请选择${item.property_name}`}>
                    {item.options && item.options.map((option: any, indexs: number) => {
                      return (
                        <Option value={option.value} key={indexs}>{option.name}</Option>
                      )
                    }
                    )}
                  </Select>
                }
                {
                  item.type === "multi_select" && <Select.SPMultiple style={{ width: 240 }} allowClear placeholder={`请选择${item.property_name}`}>
                    {item.options && item.options.map((option: any, indexa: number) => {
                      return (
                        <Select.Option value={option.value} key={indexa}>{option.name}</Select.Option>
                      )
                    })}
                  </Select.SPMultiple>
                } */}
              </Form.Item>
            )
          })}
        <Modal
          visible={showErrContentA}
          title="必填项解决办法"
          showCancel={false}
          okText=" 确定"
          // cancelText=" 取消"
          onCancel={() => setShowErrContentA(false)}
          onOk={() => setShowErrContentA(false)}>
          <div className="imageli">
            <div className="imges">
              <p>第一步：选择需要列表的商品，点击右侧发布相似品</p>
              <img
                style={{ width: "100%" }}
                src={ossurl + "funsaction/error_doc/1111120240407122707.png"}
                alt=""
              />
            </div>
            <div className="imges">
              <p>
                第二步：完成对应的必填项后（后台红色框框的地方），选择刚刚创建的商品即可列表
              </p>
              <img
                style={{ width: "100%" }}
                src={ossurl + "funsaction/error_doc/2222202404071227071.png"}
                alt=""
              />
            </div>
          </div>
        </Modal>

        <Divider />
        <h2>基础信息配置</h2>
        <Checkbox defaultChecked disabled checked>
          <Form.Item
            name="goodTitleCf"
            label="商品标题"
            tooltip="对应创建商品时的商品标题"
            rules={[{ required: true }]}>
            <Radio.Group
              onChange={(e) => {
                setCopyGoodConfig({
                  ...copyGoodConfig,
                  goodTitleCf: e.target.value * 1
                })
              }}>
              <Radio value={2}>
                拆词重组
                <Tooltip title="系统将根据当前商品标题拆分词语后重组随机生成">
                  <Icon type="DoubtIcon"></Icon>
                </Tooltip>
              </Radio>
              <Tooltip
                title={
                  !searchWord.length || searchWord.length < 50
                    ? "当前数据较少，没有推荐标题"
                    : ""
                }>
                <Radio
                  value={1}
                  disabled={!searchWord.length || searchWord.length < 50}>
                  智能标题{" "}
                  <span
                    style={{
                      color: "red"
                    }}>
                    智能标题存在一定误差建议检查后上架
                  </span>
                  <Tooltip title="系统将根据当前商品信息以及商品类目智能推荐标题,可能部分词无法通过审核，请酌情使用">
                    <Icon type="DoubtIcon"></Icon>
                  </Tooltip>
                </Radio>
              </Tooltip>
            </Radio.Group>
          </Form.Item>
        </Checkbox>
        {copyGoodConfig.goodTitleCf === 1 && (
          <TitleJiebaShers
            searchWord={searchWord}
            copyGoodConfig={copyGoodConfig}
            titleLimitRule={titleLimitRule}
            ref={getAITitleRef}
          />
        )}

        {copyGoodConfig.goodTitleCf === 2 && (
          <TitleJieba
            searchWord={searchWord}
            titleJfrStart={titleJfrStart}
            copyGoodConfig={copyGoodConfig}
            titleLimitRule={titleLimitRule}
            goodsDetellData={goodsDetellData}
            ref={getJiebaTitleRef}
          />
        )}
        <Checkbox defaultChecked disabled checked>
          <Form.Item label="商品属性" name="statsCf">
            <Radio.Group
              onChange={(e) => {
                setCopyGoodConfig({
                  ...copyGoodConfig,
                  statsCf: e.target.value * 1
                })
              }}>
              <Radio value={1}>默认</Radio>
              <Radio value={2}>手动设置</Radio>
            </Radio.Group>
          </Form.Item>
        </Checkbox>

        <div
          className="jers"
          style={{
            display: copyGoodConfig.statsCf === 2 ? "block" : "none"
          }}>
          <StatsList
            statsDataList={statsDataList}
            copyGoodConfig={copyGoodConfig}
            ref={statsDataRef}></StatsList>
        </div>
        {copyGoodConfig.statsCf === 1 && addNewProd && addNewProd.length ? (
          <Form.Item
            label={
              <>
                <span>商品属性</span>
                <span
                  className="adchoer"
                  onClick={() => {
                    setShowAddHuohao(!showAddHuohao)
                  }}
                  style={{
                    cursor: "pointer",
                    color: "#1890ff",
                    marginLeft: 10,
                    // 旋转
                    transform: showAddHuohao
                      ? "rotate(0deg)"
                      : "rotate(180deg)",
                    transition: "all 0.3s",
                    // 旋转中心
                    transformOrigin: "center center",

                    fontSize: 16
                    // display: 'inline-block',
                  }}>
                  <Icon type="DescendingOrderIcon"></Icon>
                </span>
              </>
            }
            style={{
              marginLeft: 25
            }}
            // onClick={() => {
            //   setShowAddHuohao(!showAddHuohao)
            // }}
            // tooltip="对应创建商品时的商品标题"
          >
            {addNewProd[0].find((item: any) => {
              return item.PropertyName === "货号" || item.property_id == 3171
            }) && (
              <Form.Item noStyle>
                <Space
                  style={{
                    paddingBottom: 15
                  }}>
                  <span>生成货号长度</span>
                  <InputNumber
                    value={reduterHuoDate}
                    size="small"
                    min={3}
                    max={50}
                    style={{
                      width: 80
                    }}
                    placeholder="货号随机生成长度"
                    onChange={(e: any) => {
                      setReduterHuoDate(e)
                    }}></InputNumber>
                  <Button
                    type="primary"
                    size="mini"
                    onClick={() => {
                      // const getDater = generateRandomString(reduterHuoDate)
                      // console.log('getDater', getDater)
                      // setAllNewProd(getDater)
                      addNewProd.forEach((item: any) => {
                        // console.log('item000', item)
                        item.forEach((itemDe: any, index: number) => {
                          const getDater = generateRandomString(reduterHuoDate)
                          itemDe.Name = getDater
                        })
                      })
                      setNewProd([...addNewProd])
                    }}>
                    随机生成并填充
                  </Button>
                </Space>
              </Form.Item>
            )}
            {showAddHuohao &&
              showAddHuohao &&
              addNewProd.map((item: any, index: number) => {
                return (
                  <Form.Item
                    label={"属性" + ++index}
                    key={index}
                    style={{
                      background: " #fafbfc",
                      border: "1px solid #fafbfc",
                      borderRadius: 4,
                      padding: "15px 11px 0 11px"
                      // marginLeft: 25
                    }}

                    // tooltip="对应创建商品时的商品标题"
                  >
                    <Form
                      style={{
                        marginLeft: 25
                      }}
                      layout="inline">
                      {item.map((itemDe: any, indexDe: number) => {
                        return (
                          <Form.Item
                            key={indexDe}
                            label={itemDe.PropertyName}
                            validateStatus={
                              isNaN(itemDe.Name) || !itemDe.Name ? "" : "error"
                            }
                            help={
                              isNaN(itemDe.Name) || !itemDe.Name
                                ? ""
                                : "货号不能为纯数字"
                            }>
                            <Space>
                              <Input
                                value={itemDe.Name}
                                style={{
                                  width: 200
                                }}
                                size="small"
                                maxLength={
                                  itemDe.property_id == 3171 ? 50 : 100000
                                }
                                allowClear
                                onChange={(e: any) => {
                                  itemDe.Name = e.target.value
                                  console.log("输入", itemDe.Name)
                                  setNewProd([...addNewProd])
                                }}></Input>
                              <Button
                                type="primary"
                                size="mini"
                                onClick={() => {
                                  const getDater =
                                    generateRandomString(reduterHuoDate)
                                  itemDe.Name = getDater
                                  setNewProd([...addNewProd])
                                }}>
                                随机生成
                              </Button>
                            </Space>
                          </Form.Item>
                        )
                      })}
                    </Form>
                  </Form.Item>
                  // <div key={index} style={{ display: 'flex', alignItems: 'center' }}>
                  //     {
                  //       item.map((item: any, indexDe: number) => {
                  //         return (
                  //           <div key={indexDe}>{item.PropertyName}</div>
                  //         )
                  //       })
                  //     }
                  // </div>
                )
              })}
          </Form.Item>
        ) : null}
        {/* <br />
        <Checkbox
          checked={copyGoodConfig.goodMiniTitle}
          onChange={(e: CheckboxChangeEvent) => {
            setCopyGoodConfig({
              ...copyGoodConfig,
              goodMiniTitle: e.target.checked,
              goodMiniTitleCf: e.target.checked
                ? copyGoodConfig.goodMiniTitleCf
                : 1
            })
          }}>
          <Form.Item
            // name="goodMiniTitleCf"
            label="导购短标题"
            tooltip="对应创建商品时的导购短标题">
            <Radio.Group
              value={copyGoodConfig.goodMiniTitleCf}
              disabled={!copyGoodConfig.goodMiniTitle}
              onChange={(e) => {
                setCopyGoodConfig({
                  ...copyGoodConfig,
                  goodMiniTitleCf: e.target.value * 1
                })
              }}>
              <Radio value={1}>
                默认
                <Tooltip title="将重复使用当前商品使用的内容">
                  <Icon type="DoubtIcon"></Icon>
                </Tooltip>
              </Radio>
              <Radio value={2}>
                智能推荐
                <Tooltip title="系统将根据当前商品信息以及商品类目智能推荐导购短标题">
                  <Icon type="DoubtIcon"></Icon>
                </Tooltip>
              </Radio>
            </Radio.Group>
          </Form.Item>
        </Checkbox> */}
        <Divider />
        <h2>图文信息配置</h2>
        <img src="" id="imges" alt="" />
        {/* <canvas id="mycanvas"></canvas>
        <canvas id="mycanvasee"></canvas> */}
        <Space direction="vertical" size={0}>
          <Checkbox defaultChecked disabled checked>
            <Form.Item
              label="主图"
              name="goodImageCf"
              tooltip="对应创建商品时的商品主图"
              rules={[{ required: true }]}>
              <Radio.Group
                onChange={(e) => {
                  setCopyGoodConfig({
                    ...copyGoodConfig,
                    goodImageCf: e.target.value * 1
                  })
                }}>
                <Radio value={2}>
                  【推荐使用】改图换图（添加修改边框，图标等）
                  <Tooltip title="您可自行修改主图对应信息，添加主图边框图标等">
                    <Icon type="DoubtIcon"></Icon>
                  </Tooltip>
                </Radio>
                {/* <Radio value={1}>
                  <Space>
                    AI生成
                    <Tooltip title="系统将根据当前主图智能AI算法补尝图片隐藏信息，并随机调整主图顺序">
                      <Icon type="DoubtIcon"></Icon>
                    </Tooltip>
                    {copyGoodConfig.goodImageCf === 1 && (
                      <>
                        <Switch
                          size="small"
                          checked={refoterZhutuStatus}
                          onChange={(e) => {
                            // console.log('ee', e)
                            setRefoterZhutuStatus(e)
                          }}
                        />
                        是否打乱主图顺序
                      </>
                    )}
                  </Space>
                </Radio> */}

                {/* <Radio value={3}>添加边框</Radio> */}
              </Radio.Group>
            </Form.Item>
          </Checkbox>
          {copyGoodConfig.goodImageCf === 2 && (
            <AddBodersContent
              goodsDetellData={goodsDetellData}
              copyGoodConfig={copyGoodConfig}
            />
          )}
        </Space>
        <br />
        <Checkbox
          checked={copyGoodConfig.goodImage34}
          onChange={(e: CheckboxChangeEvent) => {
            console.log(e.target.checked)
            setCopyGoodConfig({
              ...copyGoodConfig,
              goodImage34: e.target.checked,
              goodImage34Cf: e.target.checked ? copyGoodConfig.goodImage34Cf : 1
            })
          }}>
          <Form.Item
            // name="goodImage34Cf"
            label="主图 3:4"
            tooltip="对应创建商品时的商品主图 3:4">
            <Radio.Group
              disabled={!copyGoodConfig.goodImage34}
              value={copyGoodConfig.goodImage34Cf}
              onChange={(e) => {
                setCopyGoodConfig({
                  ...copyGoodConfig,
                  goodImage34Cf: e.target.value * 1
                })
              }}>
              <Radio value={2}>改图换图（添加修改边框，图标等）</Radio>
              <Radio value={1}>默认</Radio>
            </Radio.Group>
          </Form.Item>
        </Checkbox>
        {copyGoodConfig.goodImage34Cf === 2 && (
          <AddBodersContent34
            goodsDetellData={goodsDetellData}
            copyGoodConfig={copyGoodConfig}
          />
        )}
        {/*  <br />
        <Checkbox
          checked={copyGoodConfig.goodminivideo}
          onChange={(e: CheckboxChangeEvent) => {
            setCopyGoodConfig({
              ...copyGoodConfig,
              goodminivideo: e.target.checked
            })
          }}>
          <Form.Item
            // name="goodminivideo"
            label="主图视频"
            tooltip="对应创建商品时的主图视频">
          </Form.Item>
        </Checkbox>
        <br />
        <Checkbox
          checked={copyGoodConfig.goodWhitehImage}
          onChange={(e: CheckboxChangeEvent) => {
            setCopyGoodConfig({
              ...copyGoodConfig,
              goodWhitehImage: e.target.checked,
              goodWhitehImageCf: e.target.checked
                ? copyGoodConfig.goodWhitehImageCf
                : 1
            })
          }}>
          <Form.Item
            label="白底图"
            tooltip="对应创建商品时的白底图">
            <Radio.Group
              disabled={!copyGoodConfig.goodWhitehImage}
              value={copyGoodConfig.goodWhitehImageCf}
              onChange={(e) => {
                setCopyGoodConfig({
                  ...copyGoodConfig,
                  goodWhitehImageCf: e.target.value * 1
                })
              }}>
              <Radio value={1}>默认</Radio>
              <Radio value={2}>智能推荐</Radio>
            </Radio.Group>
          </Form.Item>
        </Checkbox> */}
        <br />
        {true && (
          <>
            <Checkbox defaultChecked disabled checked>
              <Form.Item
                name="goodDetelesImageCf"
                label="商品详情"
                tooltip="对应创建商品时的商品详情"
                rules={[{ required: true }]}>
                {copyGoodConfig.goodDetelesImageCf === 2 && (
                  <AddDetailsContent
                    goodPrettify={goodPrettify}
                    copyGoodConfig={copyGoodConfig}
                    goodsDetellData={goodsDetellData}
                    searchWord={searchWord}
                    searchWordMsg={searchWordMsg}
                    ref={detailsAddImageListRef}
                  />
                )}
              </Form.Item>
            </Checkbox>
          </>
        )}

        <Divider />
        <h2>价格库存</h2>
        <Checkbox
          checked={copyGoodConfig.goodSpcter}
          onChange={(e: CheckboxChangeEvent) => {
            setCopyGoodConfig({
              ...copyGoodConfig,
              goodSpcter: e.target.checked,
              goodSpcterCf: e.target.checked ? copyGoodConfig.goodSpcterCf : 1
            })
          }}>
          <Form.Item
            // name="goodSpcterCf"
            label="商品规格"
            tooltip="对应创建商品时的商品规格">
            <Radio.Group
              value={copyGoodConfig.goodSpcterCf}
              onChange={(e) => {
                setCopyGoodConfig({
                  ...copyGoodConfig,
                  goodSpcterCf: e.target.value * 1
                })
              }}
              disabled={!copyGoodConfig.goodSpcter}>
              <Radio value={2}>
                新增附加信息
                <Tooltip title="可在原有的商品规格值前后自定义加入文本信息">
                  <Icon type="DoubtIcon"></Icon>
                </Tooltip>
              </Radio>
              <Radio value={1}>
                默认
                <Tooltip title="将使用原有的规格信息">
                  <Icon type="DoubtIcon"></Icon>
                </Tooltip>
              </Radio>
            </Radio.Group>
          </Form.Item>
        </Checkbox>
        <div
          className="sbhouer"
          style={{
            display: copyGoodConfig.goodSpcterCf === 2 ? "block" : "none"
          }}>
          <SkuTitleInfoData
            goodsDetellData={goodsDetellData}
            copyGoodConfig={copyGoodConfig}
            ref={skuDataRef}
          />
        </div>
        {/* {copyGoodConfig.goodSpcterCf === 2 && (
          <SkuTitleInfoData
            goodsDetellData={goodsDetellData}
            copyGoodConfig={copyGoodConfig}
            ref={skuDataRef}
          />
        )} */}
        <br />
        <Space direction="vertical">
          <Checkbox
            checked={copyGoodConfig.goodPriceAndStock}
            onChange={(e: CheckboxChangeEvent) => {
              setCopyGoodConfig({
                ...copyGoodConfig,
                goodPriceAndStock: e.target.checked,
                goodPriceAndStockCf: e.target.checked
                  ? copyGoodConfig.goodPriceAndStockCf
                  : 1
              })
            }}>
            <Form.Item
              // name="goodPriceAndStockCf"
              label="价格与库存"
              tooltip="对应创建商品时的价格与库存">
              <Radio.Group
                value={copyGoodConfig.goodPriceAndStockCf}
                disabled={!copyGoodConfig.goodPriceAndStock}
                onChange={(e) => {
                  setCopyGoodConfig({
                    ...copyGoodConfig,
                    goodPriceAndStockCf: e.target.value * 1
                  })
                }}>
                <Radio value={2}>
                  价格配置
                  <Tooltip title="您可以根据需要配置阶梯价格，或使用一口价">
                    <Icon type="DoubtIcon"></Icon>
                  </Tooltip>
                </Radio>
                <Radio value={1}>
                  默认
                  <Tooltip title="将使用原有的价格信息">
                    <Icon type="DoubtIcon"></Icon>
                  </Tooltip>
                </Radio>
              </Radio.Group>
            </Form.Item>
          </Checkbox>
          {copyGoodConfig.goodPriceAndStockCf === 2 && (
            <PriceAndInventory
              goodsDetellData={goodsDetellData}
              copyGoodConfig={copyGoodConfig}
              ref={pricelistRef}
            />
          )}
        </Space>
        <br />
      </Form>
      <Modal
        visible={showJiaochngBox}
        title="商品裂变使用教程"
        showCancel={false}
        okText="关闭"
        destroyOnClose
        // cancelText=" 取消"
        onCancel={() => setShowJiaochngBox(false)}
        onOk={() => setShowJiaochngBox(false)}>
        <div className="imageli">
          <div className="imges">
            {showJiaochngBox && (
              <video
                controls
                autoPlay
                style={{
                  width: "100%"
                }}
                src={
                  ossurl +
                  "webimages/install_doc/In_code_vod/530_1712659497.mp4"
                }></video>
            )}
          </div>
        </div>
      </Modal>
    </>
  )
})

// 弹窗容器组件
export default function copyItemBox(props: any) {
  const dispatch = useAppDispatch()
  const {
    showCopyBox = false,
    goodsName = "",
    setShowCopyBox = () => {},
    goodid = "",
    getDataLodin = true,
    goodsDetellData = null,
    goodPrettify = null,
    titleJfrStart = null,
    searchWord = null,
    searchWordMsg = "",
    ruleData = null,
    statsDataList = null
  } = props
  if (goodsDetellData) {
    goodsDetellData.specs.forEach((res) => {
      res.values.forEach((item) => {
        item.addTep = ""
        item.direction = "left"
        item.isChecked = false
        for (let i = 0; i < goodsDetellData.spec_prices.length; i++) {
          for (
            let j = 0;
            j < goodsDetellData.spec_prices[i].sell_properties.length;
            j++
          ) {
            if (
              item.name ===
              goodsDetellData.spec_prices[i].sell_properties[j].value_name
            ) {
              // console.log('666',spec_prices[i].sell_properties[j].remark)
              item.remark =
                goodsDetellData.spec_prices[i].sell_properties[j].remark
              break
            }
          }
        }
      })
    })
  }

  const jinritemaiCopyGoods = useAppSelector(
    (state) => state.jinritemaiCopyGoods
  )
  // const addHuohaoContentData = useAppSelector( state => state.)
  const [addLodinbox, setAddLodinBox] = useState(false)
  let [current, setCurrent] = useState(0)
  const [getDataProgress, setGetDataProgress] = useState(0)
  const [getZhutuProgress, setGetZhutuProgress] = useState(0)
  const [getZhutuProgress34, setGetZhutuProgress34] = useState(0)
  const [getDeteleProgress, setGetDeteleProgress] = useState(0) // 详情图
  const [getUpGoodsProgress, setGetUpGoodsProgress] = useState(0)
  const [getZhutuProgressSku, setZhutuProgressSku] = useState(0) // sku
  const [creteteGoodsStatus, setCreteteGoodsStatus] = useState(false) // 列表完成入口
  let [upProdectStatuslisy, setUpProdectStatuslisy] = useState<any[]>([])
  const [upProdectNums, setUpProdectNums] = useState({
    success_num: 0,
    fail_num: 0
  })
  // const [up34statushoustip, setUp34statushoustip] = useState(false)
  const [showErrContent, setShowErrContent] = useState(false)
  // console.log('获取备注的情况', goodsDetellData.spec_prices, goodsDetellData.specs)
  // console.log('获取备注的情况222',
  //   JSON.stringify(goodsDetellData.spec_prices)
  //   , JSON.stringify(goodsDetellData.specs))

  // 创建上传数据
  let addConter = false
  const {
    zhutuAddImageList,
    zhutuAddImageList34,
    // detailsAddImageList,
    copyGoodConfig,
    // aiTitle,
    // jiebaTitle,
    goodsDetell,
    // skuTitleList,
    // ladderPriceList,
    // priceGroup,
    // fixedPriceList,
    addHuohaoContent,
    neircunStatus,
    refoterZhutuStatusState
  } = JSON.parse(JSON.stringify(jinritemaiCopyGoods))

  // console.log('refoterZhutuStatusState', refoterZhutuStatusState)
  // return
  const { copynum, goodTitleCf, goodSpcterCf, goodPriceAndStockCf, statsCf } =
    copyGoodConfig
  const getStetacRef = useRef<any>(null)
  async function upLoaderCreted(uptype) {
    // console.log('上传数据', getStetacRef.current.getdatersAllconte())
    // return
    let statesAter
    if (statsCf == 2) {
      statesAter = getStetacRef.current.getdatersAllconte()
      if (!statesAter || !statesAter.length) {
        message.error("请先完成属性必填项")
        return
      }
    }

    if (!neircunStatus) {
      message.error("素材库内存不足请前往设置后裂变！！")
      return
    }
    let skuTitleList = getStetacRef.current.getSkudataAllconte()
    let detailsAddImageList = getStetacRef.current.detailsAddImageListFunc()
    let jiebaTitle = getStetacRef.current.getJiebaTitle()
    let aiTitle = getStetacRef.current.getAiTitle()
    let ladderPriceList = getStetacRef.current.getLadderPriceList()
    let priceGroup = getStetacRef.current.getPriceGroup()
    let fixedPriceList = getStetacRef.current.getFixedPriceList()
    let addHuohaoContent = getStetacRef.current.getAddHuohaoContent()
    // let getdatersAllconte = getStetacRef.current.getdatersAllconte()

    // console.log('skuTitleList', getStetacRef.current, skuTitleList)
    // console.log('detailsAddImageList', ladderPriceList, priceGroup, fixedPriceList)
    // return
    const {
      outer_product_id,
      product_type,
      category_detail,
      product_format_new,
      recommend_remark,
      pay_type,
      delivery_method,
      cdf_category,
      reduce_type,
      freight_id,
      weight_value,
      weight_unit,
      delivery_delay_day,
      presell_type,
      presell_delay,
      presell_end_time,
      after_sale_service,
      mobile,
      standard_brand_id,
      out_product_id,
      quality_list,
      maximum_per_order,
      limit_per_buyer,
      minimum_per_order,
      spu_id,
      appoint_delivery_day,
      third_url,
      extra,
      src,
      poi_resource,
      car_vin_code,
      presell_config_level,
      need_recharge_mode,
      account_template_id,
      presell_delivery_type,
      white_back_ground_pic_url,
      long_pic_url,
      sell_channel,
      start_sale_type,
      delay_rule,
      material_video_id,
      pickup_method,
      size_info_template_id,
      substitute_goods_url,
      sale_channel_type,
      recruit_info,
      store_id,
      main_product_id,
      sale_limit_id,
      name_prefix,
      reference_price,
      reference_price_certificate,
      main_image_three_to_four,
      unit_price_info,
      quality_inspection_info,
      is_c2b_switch_on,
      micro_app_id,
      is_auto_charge,
      short_product_name,
      after_sale_service_v2,
      spec_info,
      spec_prices_v2,
      spec_prices,
      with_sku_type,
      name_suffix,
      use_brand_name,
      open_logistics_info,
      price_has_tax,
      biz_kind,
      main_pic_3_4,
      spec_pics,
      category_leaf_id_gt
    } = goodsDetell
    // 获取标题列表 ****
    const titles = goodTitleCf === 1 ? aiTitle : jiebaTitle

    titles.forEach((item) => {
      if (getStrLen(item.title) > 60 || getStrLen(item.title) < 15) {
        message.warning("标题长度不符合要求")
        throw new Error("标题长度不符合要求")
      }
    })
    window.onbeforeunload = function (event) {
      return "您正在AI创建商品中，是否确认离开" // 新版本浏览器不起作用
    }

    if (addConter) {
      message.warning("已开始AI创建请勿重复点击")
      return
    }
    addConter = true
    setTimeout((_) => {
      addConter = false
    }, 5000)
    addConter = true
    // 创建开始提示窗口
    setCreteteGoodsStatus(false)

    setAddLodinBox(true) // 开始创建*********
    setGetDataProgress(0)
    setGetZhutuProgress(0)
    // setGetDeteleProgress(0)
    setGetUpGoodsProgress(0)
    setGetZhutuProgress34(0)
    setZhutuProgressSku(0)
    // 获取属性值以及必填项
    let getBer = null
    if (statsCf == 1) {
      getBer = await getCatePropertyV2Api(category_leaf_id_gt)
    }

    // console.log('addHuohaoContent+++', addHuohaoContent)
    // return
    // console.log('addconter', addconter)
    // return
    setGetDataProgress(10)

    setGetDataProgress(20)
    let goodSpcterData: any = []

    function getDisplaySpecData() {
      let addFunData: any = []
      // console.log('获取备注的情况',  goodsDetellData.spec_prices, goodsDetellData.specs)
      for (let i = 0; i < copynum; i++) {
        goodsDetellData.specs.forEach((res) => {
          res.values.forEach((item) => {
            item.addTep = ""
            item.direction = "left"
            item.isChecked = false
            // for (let i = 0; i < spec_prices.length; i++) {
            //   for (let j = 0; j < spec_prices[i].sell_properties.length; j++) {
            //     if (item.name === spec_prices[i].sell_properties[j].value_name) {
            //       // console.log('666',spec_prices[i].sell_properties[j].remark)
            //       item.remark = spec_prices[i].sell_properties[j].remark
            //       break
            //     }

            //   }
            // }
          })
        })
        addFunData.push({
          list: goodsDetellData.specs,
          config: {
            direction: "left",
            addTep: "",
            isChecked: false,
            indeterminate: false
          }
        })
        // return
      }
      return addFunData
    }
    if (goodSpcterCf == 1) {
      goodSpcterData = getDisplaySpecData()
    } else if (goodSpcterCf == 2) {
      const queshi = copynum - skuTitleList.length
      goodSpcterData = JSON.parse(JSON.stringify(skuTitleList))
      if (queshi > 0) {
        for (let i = 0; i < queshi; i++) {
          const miyer: number = Math.floor(Math.random() * skuTitleList.length)
          // console.log('skuTitleList[miyer]', skuTitleList[miyer])
          goodSpcterData.push(skuTitleList[miyer])
        }
      }
    }
    // console.log('goodsDetellData.specs++**--//--++', goodsDetellData.specs)
    // return
    // console.log('goodSpcterData', goodSpcterData)
    const copycondetr = JSON.parse(JSON.stringify(goodSpcterData))
    goodSpcterData = copycondetr.map((resa) => {
      resa.list.forEach((listCont) => {
        listCont.values.forEach((item) => {
          item.bouter =
            item.direction === "left"
              ? `${item.addTep || ""}${item.name}`
              : `${item.name}${item.addTep || ""}`
        })
      })
      return resa.list
    })
    setGetDataProgress(40)
    // console.log('goodSpcterData', goodSpcterData)
    // 规格
    // console.log('ruleData', ruleData)
    const specInfo = goodSpcterData.map((res) => {
      // console.log('resresres', res)
      return {
        spec_values: res.map((item) => {
          // console.log('itemitem', item)

          return {
            property_name: item.name,
            property_id: item.property_id,
            values: item.values.map((itembe) => {
              // console.log('itembeitembe', itembe)
              let value_id
              ruleData.product_spec_rule &&
                ruleData.product_spec_rule.required_spec_details.forEach(
                  (prdids) => {
                    if (prdids.sell_property_id === item.property_id) {
                      const getPritId = prdids.property_values.find(
                        (resuer) =>
                          resuer.sell_property_value_name === itembe.bouter
                      )
                      // console.log('getPritId', getPritId)
                      if (getPritId && getPritId.sell_property_value_id) {
                        // console.log('erer', getPritId)
                        value_id = getPritId.sell_property_value_id
                      } else {
                        value_id = 0
                      }
                    }
                  }
                )
              return {
                remark: itembe.remark || "", // 需要找到备注位置
                value_name: itembe.bouter,
                value_id: value_id, //itembe.value_id,
                cpv_path: itembe.extra.cpv_path || [],
                measure_info: itembe.extra.measure_info || {}
              }
            })
          }
        })
      }
    })
    // console.log('specInfo', specInfo)
    // return
    // 规格图片
    // let specPicStr = ''
    // if (spec_pics && spec_pics.length) {
    //   const specPic = spec_pics.map(res => {
    //     return 'https://p3-aio.ecombdimg.com/obj/'+res.pic
    //   })
    //   specPicStr = specPic.join(',')
    // }
    // console.log('specPicStrspecPicStr', specPicStr)
    let goodPriceAndStock: any = []
    if (goodPriceAndStockCf == 1) {
      for (let i = 0; i < copynum; i++) {
        goodPriceAndStock.push({
          add_type: 4,
          price: ""
        })
      }
    } else if (goodPriceAndStockCf == 2) {
      if (priceGroup === 1) {
        // 阶梯
        goodPriceAndStock = JSON.parse(JSON.stringify(ladderPriceList))
        const outerNums = copynum - ladderPriceList.length
        if (outerNums > 0) {
          for (let i = 0; i < outerNums; i++) {
            const miyer: number = Math.floor(
              Math.random() * ladderPriceList.length
            )
            goodPriceAndStock.push(ladderPriceList[miyer])
          }
        }
      } else if (priceGroup === 2) {
        goodPriceAndStock = JSON.parse(JSON.stringify(fixedPriceList))
        const outerNums = copynum - fixedPriceList.length
        if (outerNums > 0) {
          for (let i = 0; i < outerNums; i++) {
            const miyer: number = Math.floor(
              Math.random() * fixedPriceList.length
            )
            goodPriceAndStock.push(fixedPriceList[miyer])
          }
        }
      }
    }
    // console.log('***---odPr/\-kgoodPriceAndStock', goodPriceAndStock)
    setGetDataProgress(80)

    // 添加 spec_prices_v2 信息
    let specPricesV2 = goodPriceAndStock.map((res, index) => {
      const lipdata: any = []
      spec_prices &&
        spec_prices.forEach((itemspec) => {
          const pricesUpData: any = {
            sku_status: itemspec.sku_status,
            sku_type: itemspec.sku_type,
            stock_num: itemspec.stock_num,
            price: (() => {
              const { add_type, price } = res
              if (add_type === 1) {
                if (price) {
                  return Math.floor(itemspec.price + price * 100)
                }
              }
              if (add_type === 2) {
                if (price) {
                  const miher = Math.floor(itemspec.price - price * 100)
                  return miher <= 1 ? 1 : miher
                }
              }
              if (add_type === 3) {
                if (price) {
                  return Math.floor(price * 100) <= 1
                    ? 1
                    : Math.floor(price * 100)
                }
              }
              if (add_type === 4) {
                return itemspec.price
              }
              return itemspec.price
            })(), // 价格 需要改
            code: itemspec.code,
            step_stock_num: itemspec.step_stock_num,
            supplier_id: itemspec.supplier_id,
            out_sku_id: itemspec.out_sku_id,
            // outer_sku_id: itemspec.out_sku_id,
            customs_report_info: itemspec.customs_report_info,
            stock_num_map: itemspec.stock_num_map,
            package_sku: itemspec.package_sku || [],
            tax_exemption_sku_info: itemspec.tax_exemption_sku_info || {},
            spec_value_lib_id: itemspec.spec_value_lib_id,
            presell_delay: itemspec.presell_delay,
            barcodes: itemspec.barcodes || [],
            cargo: itemspec.cargo_info || {},
            delivery_infos: itemspec.delivery_infos || [],
            supply_price: itemspec.supply_price,
            sell_properties: itemspec.sell_properties.map((conter, iterdex) => {
              let property_name = conter.property_name
              let value_name = ""
              const findNames = goodSpcterData[index].find(
                (item) => item.name === conter.property_name
              )
              if (findNames) {
                const getOyer = findNames.values.find(
                  (item) => item.name === conter.value_name
                )
                value_name = getOyer.bouter
              }
              return {
                property_name: property_name,
                value_name: value_name
              }
            }), // 规格信息 需要匹配
            gold_process_charge: itemspec.gold_process_charge,
            sku_classification_type: itemspec.sku_classification_type
          }

          lipdata.push(pricesUpData)
        })
      return lipdata
    })
    // console.log('specPricesV2', specPricesV2)
    // console.log('specInfo', specInfo)
    // 主图4:3
    // let mainPic43 = ""
    // if (main_pic_3_4 && main_pic_3_4.length) {
    //   mainPic43 = main_pic_3_4.join("|")
    // }
    // console.log('mainPic43', mainPic43)
    setGetDataProgress(100)
    setCurrent(current++)
    // return
    // 主图
    setGetZhutuProgress(0)
    // console.log('zhutuAddImageList', zhutuAddImageList)
    // return
    const doudianZhutuUrlList = await setImageInfoDtatFun(
      zhutuAddImageList,
      copyGoodConfig,
      1,
      (stip) => {
        setGetZhutuProgress(stip)
      },
      refoterZhutuStatusState
    )
    setCurrent(current++)

    setGetZhutuProgress(100)
    // 3:4
    let set34ImageData = await setImageInfoDtatFun(
      zhutuAddImageList34,
      copyGoodConfig,
      3,
      (stip) => {
        // setGetZhutuProgress(stip)
        setGetZhutuProgress34(stip)
      }
    )
    setGetZhutuProgress34(100)
    // sku图片
    const skuUplistInfo = skuTitleList.map((skuImga, index) => {
      const skuImageData = {
        config: {
          selectType: ""
        },
        list: []
      }
      skuImageData.config.selectType =
        skuImga.list[0] && skuImga.list[0].config.selectType
      skuImageData.list =
        skuImga.list[0] &&
        skuImga.list[0].values.map((skuImgaeItemConfig) => {
          return skuImgaeItemConfig.picImga
        })
      return skuImageData
    })

    const doudlianSkuimage = await setImageInfoDtatFun(
      skuUplistInfo,
      copyGoodConfig,
      4,
      (stip) => {
        // console.log('sku进度', stip)
        setZhutuProgressSku(stip)
        // setGetZhutuProgress(stip)
      }
    )
    setZhutuProgressSku(100)
    // console.log('doudlianSkuimage', doudlianSkuimage)
    // console.log('set34ImageData', set34ImageData)
    // setUp34statushoustip(set34ImageData)
    if (set34ImageData == false) {
      set34ImageData = []
      for (let iuy = 0; iuy < copynum; iuy++) {
        let mainPic43 = ""
        if (main_pic_3_4 && main_pic_3_4.length) {
          mainPic43 = main_pic_3_4.join("|")
        }
        set34ImageData.push(mainPic43)
      }
      // set34ImageData
      // console.log('默认情况')
    } else {
      set34ImageData = set34ImageData.map((resitem) => {
        return resitem
          .filter((bsterurl) => {
            return bsterurl.byte_url
          })
          .map((ityer) => {
            return ityer.byte_url
          })
          .join("|")
      })
    }
    setGetZhutuProgress34(100)
    // console.log('3:4效果', set34ImageData)
    // return
    // setCurrent(2)

    // //  详情
    // // return
    // setGetDeteleProgress(19)
    // // const upInDetailsDoudian: any = await setImageInfoDtatFun(detailsAddImageList, copyGoodConfig, 2)
    // setGetDeteleProgress(53)
    // // 处理完成后获取抖店的素材详情
    // // const doudianXiangqiUrlList:any = await asycGetImageStatus(upInDetailsDoudian.getOssPutDouDian, upInDetailsDoudian.upListData)
    // // setTimeout(_ => {
    // //   setGetDeteleProgress(68)
    // // }, 1350)
    // setGetDeteleProgress(100)
    setCurrent(current++)

    // console.log('主图', doudianZhutuUrlList)
    // console.log('详情图', doudianXiangqiUrlList)
    // console.log('detailsAddImageList', detailsAddImageList)
    // const getLiter:any = []
    // for (let i = 0; i < copynum; i++) {
    //   getLiter.push(detailsAddImageList[0])
    // }
    // 上传创建商品
    const upGoodsList: any = []
    // setGetUpGoodsProgress(10)
    const upDataOrder: any = []
    for (let index = 0; index < copynum; index++) {
      let picStr = ""
      const mapDataerconter = doudianZhutuUrlList[index].map((res) => {
        return res.byte_url
      })
      picStr = mapDataerconter.join("|")
      let descriptionStr = ""

      // const mapDataerconter2 = detailsAddImageList[index].map(res => {
      //   console.log('rererezhutu ', res)
      //   return res.url
      // })
      // console.log('mapDataerconter2', detailsAddImageList)
      // descriptionStr = mapDataerconter2.join('|')
      // const mapDataerconter2 = doudianXiangqiUrlList[index].map(res => {
      //   return res.byte_url
      // })
      // console.log('descriptionStr222', mapDataerconter)
      // 详情图未做处理****
      descriptionStr = detailsAddImageList[index].list
        .map((ressr) => ressr.url)
        .join("|")
      // console.log('descriptionStr', descriptionStr)
      // console.log('doudlianSkuimage', doudlianSkuimage)
      let specPicStr = doudlianSkuimage[index]
        .filter((sukuImages) => sukuImages.byte_url)
        .map((itter) => itter.byte_url)
        .join(",")
      // console.log('specPicStr', specPicStr)
      // specInfo[index].spec_values[0].values.forEach((item, index) => {
      //   if (spec_pics && spec_pics.length) {
      //     spec_pics[index] = spec_pics[index] || spec_pics[0] //{pic:''}
      //   }
      // })
      // console.log('spec_pics', spec_pics)
      // if (spec_pics && spec_pics.length) {
      //   const specPic = spec_pics.map((res) => {
      //     return res.pic && "https://p3-aio.ecombdimg.com/obj/" + res.pic
      //   })
      //   specPicStr = specPic.join(",")
      // }
      // console.log('specPicStrspecPicStr', specPicStr)
      // return
      let addconterNew
      if (statsCf == 1) {
        addconterNew = JSON.parse(product_format_new)
        if (getBer.code === 10000) {
          const ads = getBer.data.data

          ads &&
            ads.forEach((item, indexa) => {
              let property_id = item.property_id + ""

              property_id &&
                addconterNew[property_id] &&
                addconterNew[property_id].forEach((sx) => {
                  if (item.diy_type === 1) {
                    let luer = item.options.find(
                      (opt) => opt.value_id == sx.Value
                    )

                    if (!luer) {
                      sx.diy_type = 1
                    }
                  }
                })
              if (property_id == "4032" && addconterNew[property_id]) {
                delete addconterNew[property_id]
              }

              if (item.required) {
                // console.log('必填项, 检查是否填写， 最总需要报错')
              }
              if (property_id == "3171") {
                addconterNew["3171"] = addHuohaoContent[index]
              }
            })
        } else {
          message.error("获取属性值失败")
          throw new Error("获取属性值失败")
        }
      }

      // return
      const cretedData = {
        // outer_product_id, // 外部使用id 可以不传
        product_type,
        category_leaf_id: category_leaf_id_gt,
        product_format_new:
          statsCf == 2
            ? JSON.stringify(statesAter[index])
            : JSON.stringify(addconterNew), // 属性
        name: titles[index].title, // 上面处理过的标题*
        recommend_remark, // 代购
        pic: picStr, // 上面处理过的主图*
        description: descriptionStr, // 上面处理过的详情*
        pay_type,
        delivery_method,
        cdf_category,
        reduce_type,
        assoc_ids: "", // 推荐品 可不填
        freight_id,
        weight: weight_value, // 重量 无可不填
        weight_unit,
        delivery_delay_day,
        presell_type,
        presell_delay,
        presell_end_time,
        after_sale_service: (() => {
          let dater = {
            supply_day_return_selector: ""
          }
          try {
            const getDater = JSON.parse(after_sale_service)
            dater.supply_day_return_selector =
              getDater.supply_day_return_selector
          } catch (error) {
            console.log("售后字段")
          }
          return JSON.stringify(dater)
        })(), // 老字段 可能废弃
        mobile,
        commit: true, // 直接发布
        standard_brand_id, // 新的品牌ID
        remark: "", // 商家可见备注
        // out_product_id, // 外部使用id 可以不传
        quality_list,
        // spec_name: '', // 上面处理过规格* 使用spec_info替换
        // specs: '', // 上面处理过规格* 使用spec_info 替换
        // spec_prices: '', // 上面处理过价格与库存* 使用spec_prices替换
        spec_pic: specPicStr, // 上面处理过规格图片*
        maximum_per_order,
        limit_per_buyer,
        minimum_per_order,
        spu_id,
        appoint_delivery_day,
        third_url, // /\/\
        extra,
        src, // /\/\
        need_check_out: true, // 卡券类型需要传true
        poi_resource, // /\/\ 卡券信息
        car_vin_code,
        presell_config_level,
        need_recharge_mode,
        account_template_id,
        presell_delivery_type,
        white_back_ground_pic_url,
        long_pic_url,
        sell_channel,
        start_sale_type: uptype,
        delay_rule,
        material_video_id,
        pickup_method,
        size_info_template_id,
        substitute_goods_url, // /\/\
        sale_channel_type,
        recruit_info, // /\/\
        store_id,
        main_product_id,
        sale_limit_id,
        name_prefix, // 通过/product/getRecommendName接口推荐的商品标题前缀（注意系统根据类目属性生成前缀字符串时，末尾有一个空格）
        reference_price,
        reference_price_certificate, // /\/\
        main_image_three_to_four: set34ImageData[index], // 主图4:3 考虑需不需要生成*
        unit_price_info, // /\/\
        quality_inspection_info, // /\/\
        is_c2b_switch_on, // /\/\
        micro_app_id,
        is_auto_charge, // /\/\
        short_product_name: titles[index].miniTitle, // 导购短语， 后期自动生成
        after_sale_service_v2: (() => {
          const adder: any = {
            is_large_product: after_sale_service_v2.is_large_product
          }
          if (after_sale_service_v2.three_guarantees) {
            adder.three_guarantees = {
              service_type: after_sale_service_v2.three_guarantees.service_type,
              duration:
                after_sale_service_v2.three_guarantees.service_type == 1 &&
                after_sale_service_v2.three_guarantees.duration === 180
                  ? 365
                  : after_sale_service_v2.three_guarantees.duration
            }
          }

          // three_guarantees: after_sale_service_v2.three_guarantees && {

          // }
          return adder
        })(), // 前期需要从after_sale_service获取数据
        spec_info: specInfo[index], // 规格详细信息，代替specs和spec_name
        spec_prices_v2: specPricesV2[index], // 新sku参数，代替spec_prices
        with_sku_type, // /\/\
        name_suffix,
        use_brand_name, // 是否勾选使用品牌名, 注意勾选时需要接入/product/getRecommendName接口
        open_logistics_info, // /\/\
        price_has_tax,
        biz_kind // /\/\
      }
      upDataOrder.push(cretedData)
      // console.log('cretedData', cretedData)
      // upGoodsList.push(publishProductApi(cretedData))
    }
    if (quality_list && quality_list.length) {
      upProdectStatuslisy = []
      putDateinter(JSON.parse(JSON.stringify(upDataOrder)), 0)
    } else {
      setGetUpGoodsProgress(13)
      const upGoodsListPro = upDataOrder.map((itempro) =>
        publishProductApi(itempro)
      )
      setGetUpGoodsProgress(50)
      const upeDaterLier = await Promise.all(upGoodsListPro)
      setGetUpGoodsProgress(100)
      setCurrent(current++)
      setCreteteGoodsStatus(true)
      //  console.log('创建结果', upGoodsListPro)
      upProdectStatuslisy = []
      upeDaterLier.forEach((item, index) => {
        // console.log('itemitemitem', item)
        upDataOrder[index].upstatus = item
        item.name = upDataOrder[index].name
        if (item.code === 10000) {
          upProdectNums.success_num++
        } else {
          upProdectNums.fail_num++
        }
        upProdectStatuslisy.push(item)
      })
      setUpProdectNums(upProdectNums)
      setUpProdectStatuslisy([...upProdectStatuslisy])
      // console.log("上传元数据及结果", upDataOrder)
    }
    async function putDateinter(data, index) {
      const getcyae = data.splice(0, 1)
      if (getcyae[0]) {
        const updata = await publishProductApi(getcyae[0])
        // console.log('updataupdata', updata)
        setGetUpGoodsProgress(
          Math.round(
            ((upDataOrder.length - data.length) / upDataOrder.length) * 100
          )
        )
        updata.name = getcyae[0].name
        upDataOrder[index].upstatus = updata
        if (updata.code === 10000) {
          upProdectNums.success_num++
        } else {
          upProdectNums.fail_num++
        }
        setUpProdectNums(upProdectNums)
        upProdectStatuslisy.push(updata)
        putDateinter(data, index++)
      } else {
        console.log("创建完成")
        setGetUpGoodsProgress(100)
        setCurrent(current++)
        setUpProdectStatuslisy([...upProdectStatuslisy])
        // upDataOrder.forEach((item, index) => {
        //   console.log('itemitemitem', item)
        //   // upDataOrder[index].upstatus = item
        // })
        setCreteteGoodsStatus(true)
      }
    }
    window.onbeforeunload = null
  }

  return (
    <>
      <Drawer
        destroyOnClose={true}
        visible={showCopyBox}
        title={`裂变：${goodsName}`}
        onCancel={() => setShowCopyBox(false)}
        className="copyConfigBox"
        width={1200}
        footer={
          <>
            <div
              className="er"
              style={{
                display: "flex",
                justifyContent: "flex-end"
              }}>
              <Space align="end">
                {goodTitleCf === 2 && (
                  <Button
                    icon={<Icon type="LocalUploadIcon"></Icon>}
                    type="primary"
                    onClick={() => {
                      if (
                        getDataLodin ||
                        !goodsDetellData ||
                        !goodsDetellData.product_id
                      ) {
                        message.warning("正在准备数据！！！")
                        return
                      }
                      if (
                        goodsDetellData.addRequData &&
                        goodsDetellData.addRequData.length
                      ) {
                        message.warning("请前往完善商品信息后开始裂变")
                        return
                      }
                      upLoaderCreted(0)
                    }}>
                    立即上架
                  </Button>
                )}

                <Button
                  icon={<Icon type="CommodityIcon"></Icon>}
                  type="primary"
                  onClick={() => {
                    if (
                      getDataLodin ||
                      !goodsDetellData ||
                      !goodsDetellData.product_id
                    ) {
                      message.warning("正在准备数据！！！")
                      return
                    }
                    if (
                      goodsDetellData.addRequData &&
                      goodsDetellData.addRequData.length
                    ) {
                      message.warning("请前往完善商品信息后开始裂变")
                      return
                    }
                    upLoaderCreted(1)
                  }}>
                  放入仓库
                </Button>
                <Button
                  onClick={() => {
                    setShowCopyBox(false)
                  }}>
                  取消
                </Button>
              </Space>
            </div>
          </>
        }
        // footer={!getDataLodin || goodsDetellData && goodsDetellData.product_id }
        onOk={() => {
          if (getDataLodin || !goodsDetellData || !goodsDetellData.product_id) {
            message.warning("正在准备数据！！！")
            return
          }
          if (
            goodsDetellData.addRequData &&
            goodsDetellData.addRequData.length
          ) {
            message.warning("请前往完善商品信息后开始裂变")
            return
          }
          upLoaderCreted(0)
        }}>
        {getDataLodin ? (
          <div className="lodingbox">
            <Spin></Spin>
          </div>
        ) : goodsDetellData && goodsDetellData.product_id ? (
          <ShowDataBox
            goodsDetellData={goodsDetellData}
            goodPrettify={goodPrettify}
            titleJfrStart={titleJfrStart}
            searchWord={searchWord}
            searchWordMsg={searchWordMsg}
            ruleData={ruleData}
            statsDataList={statsDataList}
            ref={getStetacRef}
          />
        ) : (
          <Empty className="empty-img-emotion" description="繁忙，请稍后再试" />
        )}
        <Popover
          placement="topRight"
          content={
            <div className="imagesBox">
              <ImgDefault
                mask={false}
                borderRadius={8}
                style={{ width: 88, height: 88, margin: "0 auto 10px" }}
                // src={goodPrettify.pic}
                imgSrc={
                  ossurl +
                  "webimages/code/WechatIMG6.jpg?time=" +
                  new Date().getTime()
                }></ImgDefault>
              <p
                style={{
                  fontSize: 12
                  // color: '#999',
                }}>
                扫码联系客服反馈
              </p>
            </div>
          }>
          <div className="codeBdoer">
            <Icon type="CustomerServiceIcon"></Icon>
            联系客服
          </div>
        </Popover>
      </Drawer>
      <Drawer
        destroyOnClose={true}
        visible={addLodinbox}
        closable={creteteGoodsStatus}
        onCancel={() => {
          setShowCopyBox(false)
          setAddLodinBox(false)
        }}
        width={1200}
        title="创建中"
        // size="large"

        footer={null}
        maskClosable={creteteGoodsStatus}>
        <div className="moberDater">
          {creteteGoodsStatus ? (
            <div className="conterTer">
              <Space direction="vertical" size={15} align="center">
                <div
                  className="svgScuers"
                  style={{
                    textAlign: "center"
                  }}>
                  <svg
                    width="120"
                    height="120"
                    viewBox="0 0 120 120"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg">
                    <g clip-path="url(#clip0_445_33713)">
                      <path
                        fill-rule="evenodd"
                        clip-rule="evenodd"
                        d="M60 93C78.2254 93 93 78.2254 93 60C93 41.7746 78.2254 27 60 27C41.7746 27 27 41.7746 27 60C27 78.2254 41.7746 93 60 93ZM77.6492 53.4642C79.1589 51.49 78.7823 48.6658 76.8081 47.1561C74.8339 45.6464 72.0097 46.023 70.5 47.9972L55.4514 66.1288L48.5523 58.7345C47.0265 56.7727 44.1992 56.4193 42.2375 57.9451C40.2757 59.471 39.9223 62.2982 41.4481 64.26L51.9295 76.26C52.786 77.3613 54.1049 78.003 55.5 77.9973C56.8951 77.9915 58.2087 77.3391 59.0562 76.2308L77.6492 53.4642Z"
                        fill="#397BFF"
                      />
                      <path
                        opacity="0.1"
                        fill-rule="evenodd"
                        clip-rule="evenodd"
                        d="M22.5 2C22.5 0.895431 21.6046 0 20.5 0H15.5C14.3954 0 13.5 0.895431 13.5 2L13.5 13.5H2C0.895431 13.5 0 14.3954 0 15.5V20.5C0 21.6046 0.895431 22.5 2 22.5H13.5L13.5 34C13.5 35.1046 14.3954 36 15.5 36H20.5C21.6046 36 22.5 35.1046 22.5 34V22.5H34C35.1046 22.5 36 21.6046 36 20.5V15.5C36 14.3954 35.1046 13.5 34 13.5H22.5V2Z"
                        fill="#397BFF"
                      />
                      <path
                        opacity="0.3"
                        fill-rule="evenodd"
                        clip-rule="evenodd"
                        d="M113.25 68C113.25 66.8954 112.355 66 111.25 66H110.75C109.645 66 108.75 66.8954 108.75 68V72.75H104C102.895 72.75 102 73.6454 102 74.75V75.25C102 76.3546 102.895 77.25 104 77.25H108.75V82C108.75 83.1046 109.645 84 110.75 84H111.25C112.355 84 113.25 83.1046 113.25 82V77.25H118C119.105 77.25 120 76.3546 120 75.25V74.75C120 73.6454 119.105 72.75 118 72.75H113.25V68Z"
                        fill="#397BFF"
                      />
                      <path
                        opacity="0.4"
                        fill-rule="evenodd"
                        clip-rule="evenodd"
                        d="M76.7734 104C76.7734 102.895 75.878 102 74.7734 102H74.2734C73.1689 102 72.2734 102.895 72.2734 104V108.75H67.5234C66.4189 108.75 65.5234 109.645 65.5234 110.75V111.25C65.5234 112.355 66.4189 113.25 67.5234 113.25H72.2734V118C72.2734 119.105 73.1689 120 74.2734 120H74.7734C75.878 120 76.7734 119.105 76.7734 118V113.25H81.5234C82.628 113.25 83.5234 112.355 83.5234 111.25V110.75C83.5234 109.645 82.628 108.75 81.5234 108.75H76.7734V104Z"
                        fill="#397BFF"
                      />
                    </g>
                    <defs>
                      <clipPath id="clip0_445_33713">
                        <rect width="120" height="120" fill="white" />
                      </clipPath>
                    </defs>
                  </svg>
                </div>
                <div className="conters">
                  列表完成:{" "}
                  {upProdectNums.success_num !== 0 &&
                    `${upProdectNums.success_num} 条成功`}
                  {upProdectNums.fail_num !== 0 &&
                    `${upProdectNums.fail_num} 条失败`}
                  {/* 成功裂变{jinritemaiCopyGoods.goodsDetell.copynum}个商品 */}
                </div>
                <Space size={8} align="center">
                  <Button
                    type="primary"
                    onClick={() => {
                      open(
                        "https://fxg.jinritemai.com/ffa/creative/tools?materialType=24"
                      )
                    }}>
                    我要投稿
                  </Button>
                  <Button onClick={() => setAddLodinBox(false)}>
                    继续裂变
                  </Button>
                  <Button
                    onClick={() => {
                      setShowCopyBox(false)
                      setAddLodinBox(false)
                      const shcerDater: any =
                        document.querySelector(".ecom-g-btn-dashed")
                      shcerDater && shcerDater.click()
                    }}>
                    返回商品列表
                  </Button>
                  <Button
                    onClick={() => dispatch(AutoTk(""))}
                    icon={<Icon type="OrderExportIcon"></Icon>}>
                    自动拍单
                  </Button>
                  <Button
                    style={{
                      marginLeft: 10
                    }}
                    onClick={() => {
                      window.open("http://dym.11daifa.com/")
                    }}>
                    <img
                      src="https://dym.11daifa.com/favicon.ico"
                      style={{
                        width: 16,
                        height: 16,
                        marginRight: 5,
                        marginBottom: 3
                      }}
                    />
                    礼品网
                  </Button>
                </Space>
                {upProdectStatuslisy && upProdectStatuslisy.length && (
                  <div className="jieguobox">
                    {upProdectStatuslisy.map((item: any, index) => {
                      return (
                        <div
                          key={index}
                          className={
                            "tebconter" +
                            (item.code === 10000
                              ? " tebcontersuccess"
                              : " tebconterfail")
                          }>
                          <div className="numage">
                            商品状态: {item.code === 10000 ? "成功" : "失败"}
                          </div>
                          {item.code === 10000 && (
                            <div className="idpro">
                              创建商品id: {item.data.product_id}
                            </div>
                          )}
                          <div className="numage">商品标题: {item.name}</div>
                          {item.code !== 10000 && (
                            <div className="errbose">
                              失败原因: {item.sub_msg}
                            </div>
                          )}
                          {/* <div className="errbose">
                              解决办法:
                              <Button
                                type="link"
                                onClick={() => {
                                  setShowErrContent(true)
                                }}>
                                查看解决办法
                              </Button>
                            </div> */}
                          {item.code !== 10000 && (
                            <div className="errbose">
                              解决办法:
                              <Button
                                type="link"
                                onClick={() => {
                                  setShowErrContent(true)
                                }}>
                                查看解决办法
                              </Button>
                            </div>
                          )}
                        </div>
                      )
                    })}
                  </div>
                )}
                <Modal
                  visible={showErrContent}
                  title="发布失败解决办法"
                  showCancel={false}
                  okText=" 确定"
                  // cancelText=" 取消"
                  onCancel={() => setShowErrContent(false)}
                  onOk={() => setShowErrContent(false)}>
                  <div className="imageli">
                    <div className="imges">
                      <p>第一步：选择需要列表的商品，点击右侧发布相似品</p>
                      <img
                        style={{ width: "100%" }}
                        src={
                          ossurl +
                          "funsaction/error_doc/1111120240407122707.png"
                        }
                        alt=""
                      />
                    </div>
                    <div className="imges">
                      <p>
                        第二步：完成对应的必填项后（后台红色框框的地方），选择刚刚创建的商品即可列表
                      </p>
                      <img
                        style={{ width: "100%" }}
                        src={
                          ossurl +
                          "funsaction/error_doc/2222202404071227071.png"
                        }
                        alt=""
                      />
                    </div>
                  </div>
                </Modal>
              </Space>
            </div>
          ) : (
            <Space direction="vertical" size={15}>
              <div
                className="lofinmas"
                style={{
                  margin: "0 auto 10px",
                  // width: '80%',
                  textAlign: "center"
                }}>
                <Spin size="large" />
              </div>
              <h2
                style={{
                  textAlign: "center"
                }}>
                正在AI创建商品请勿关闭或刷新浏览器，窗口
              </h2>
              <Steps
                current={current}
                upDone={true}
                // style={{
                //   width: "80%",
                //   margin: "0 auto"
                // }}
              >
                <Step
                  title="收集数据"
                  description={
                    <Progress
                      type="circle"
                      percent={getDataProgress}
                      width={60}
                    />
                  }
                />
                <Step
                  title="AI处理"
                  description={
                    <Progress
                      type="circle"
                      percent={getZhutuProgress}
                      width={60}
                    />
                  }
                />
                {jinritemaiCopyGoods.copyGoodConfig.goodImage34Cf != 1 && (
                  <Step
                    title="AI处理主图3:4"
                    description={
                      <Progress
                        type="circle"
                        percent={getZhutuProgress34}
                        width={60}
                      />
                    }
                  />
                )}
                <Step
                  title="AI处理SKU图片"
                  description={
                    <Progress
                      type="circle"
                      percent={getZhutuProgressSku}
                      width={60}
                    />
                  }
                />
                {/* <Step title="处理详情图"
                  description={<Progress type="circle" percent={getDeteleProgress} width={60} />} /> */}
                <Step
                  title="发布商品"
                  description={
                    <Progress
                      type="circle"
                      percent={getUpGoodsProgress}
                      width={60}
                    />
                  }
                />
              </Steps>
            </Space>
          )}
        </div>
      </Drawer>
    </>
  )
}
